const _ = require('underscore');
const codeMap = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

exports.distanceForShow = function(distance) {
  distance = distance || 0;
  if (distance < 1000) return distance + '米';
  else if (distance > 1000)
    return (Math.round(distance / 100) / 10).toFixed(1) + '公里';
};

exports.n2s = function(num) {
  num = num + '';
  num = num.split('');

  let newArr = [];

  _.each(num, function(v, k) {
    newArr.push(codeMap[v]);
  });

  return newArr.join('');
};

exports.s2n = function(str) {
  str = str + '';
  str = str.split('');

  let newArr = [];

  _.each(str, function(v, k) {
    newArr.push(codeMap.indexOf(v));
  });

  return newArr.join('');
};

const zeroPadding = (exports.zeroPadding = function(n, pad) {
  let i,
    l,
    r = '';
  n = n + '';

  if (n.length < pad) {
    l = pad - n.length;
    for (i = 0; i < l; i++) {
      r += '0' + n;
    }
  } else {
    r = n;
  }

  return r;
});

exports.getBeginDate = function() {
  const now = new Date();
  const year = now.getFullYear();
  const month = zeroPadding(now.getMonth() + 1, 2);
  const date = zeroPadding(now.getDate(), 2);

  return year + '-' + month + '-' + date;
};

exports.getEndDate = function(delayMonth) {
  delayMonth = delayMonth || 3;
  const now = new Date();
  let year, month, date;

  month = now.getMonth();
  now.setMonth(month + delayMonth);
  year = now.getFullYear();
  month = zeroPadding(now.getMonth() + 1, 2);
  date = zeroPadding(now.getDate(), 2);

  return year + '-' + month + '-' + date;
};

exports.parseQuery = function(queryString) {
  let params = {},
    idx;
  (queryString = queryString || ''), (idx = queryString.indexOf('?'));

  if (idx > -1) {
    queryString = queryString.slice(idx + 1);
  } else {
    queryString = '';
  }

  if (queryString) {
    queryString = queryString.split('&');
    let i, l, q, key, value;
    for (i = 0, l = queryString.length; i < l; i++) {
      q = queryString[i];
      q = q.split('=');
      key = q[0];
      value = q[1];
      params[key] = value;
    }
  }

  return params;
};

exports.object2query = function(obj = {}) {
  let params = '';

  Object.entries(obj).forEach(([k, v]) => {
    // if (!v) return;

    params += `${k}=${encodeURIComponent(v)}&`;
  });

  params = params.replace(/&$/, '');

  if (params != '') params = '?' + params;

  return params;
};

exports.round2 = function(num, precision) {
  num = num || 0;
  precision = precision || 2;

  const dnum = Math.pow(10, precision);

  if (
    Math.floor(num * dnum * 10) % 5 == 0 &&
    Math.floor(num * dnum * 10) == num * dnum * 10 &&
    Math.floor(num * dnum) % 2 == 0
  ) {
    return Math.floor(num * dnum) / dnum;
  } else {
    return Math.round(num * dnum) / dnum;
  }
};

exports.trim = function(str) {
  return (str + '').replace(/^\s+|\s+$/g, '');
};

exports.spiderDetect = function(ua, ip) {
  const re = /googlebot|baiduspider|yahoo!|yodaobot|msnbot|360spider|bingbot/i;
  const match = ua.match(re);

  if (match) {
    return match[0];
  } else {
    return null;
  }
};

exports.json = {
  encode: function(obj) {
    let r = '';

    try {
      r = JSON.stringify(obj);
    } catch (err) {}

    return r;
  },

  decode: function(str) {
    let r = undefined;

    try {
      r = JSON.parse(str);
    } catch (err) {}

    return r;
  }
};

exports.defaultParams = {};

exports.timestamp = function() {
  return Math.round(new Date() / 1000);
};

exports.jstimestamp = function() {
  return +new Date();
};

exports.signature = function(obj, random) {
  if (!obj || !random) {
    throw new Error('Signature: missing parameters!');
  }

  let keys = [];
  let signString = '';
  let signature = '';

  keys = Object.keys(obj).sort();

  keys.forEach(function(key) {
    if (key && obj[key] !== '') {
      //signString += key + '=' + encodeURIComponent(obj[key]) + '&';
      signString += key + '=' + obj[key] + '&';
    }
  });

  signString += random;
  signature = this.md5(signString);

  return signature;
};

exports.errors = function(errors) {
  var keys = Object.keys(errors);
  var errs = [];

  if (!keys) {
    return ['Oops! There was an error'];
  }

  keys.forEach(function(key) {
    if (errors[key]) errs.push(errors[key].message);
  });

  return errs;
};

exports.indexof = function(arr, obj) {
  let index = -1;
  const keys = Object.keys(obj);

  const result = arr.filter(function(doc, idx) {
    let matched = 0;

    for (let i = keys.length - 1; i >= 0; i--) {
      if (doc[keys[i]] === obj[keys[i]]) {
        matched++;

        if (matched === keys.length) {
          index = idx;
          return idx;
        }
      }
    }
  });

  return index;
};

exports.findByParam = function(arr, obj, cb) {
  const index = exports.indexof(arr, obj);

  if (~index && typeof cb === 'function') {
    return cb(undefined, arr[index]);
  } else if (~index && !cb) {
    return arr[index];
  } else if (!~index && typeof cb === 'function') {
    return cb('not found');
  }
};

exports.getErrorMessage = function(errObj) {
  if (errObj == null) return '接口数据返回格式有误';

  let r = '';

  try {
    r = errObj.code || errObj.result.error_msg || errObj.result.error_code;
  } catch (err) {
    r = '';
  }

  return r;
};

exports.getLocalDateString = function(dateStr) {
  var r, t, re, fullYear, month, dateArr, date, days, day;
  days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  t = new Date();
  re = /(\d+)-(\d+)-(\d+)/;
  dateArr = dateStr.match(re);
  fullYear = dateArr[1];
  month = dateArr[2] - 0;
  date = dateArr[3] - 0;
  r = '' + fullYear + '年';
  r += month + '月';
  r += date + '日';

  t = new Date(fullYear, month - 1, date);

  day = t.getDay();
  r += ' ' + days[day];

  return r;
};

exports.stripScripts = function(str) {
  if (!str) return '';

  if (typeof str !== 'string') return '';

  if (/<script[^>]*>([\s\S]*?)<\/script>/.test(str)) {
    return '';
  }

  return str.replace(/<|>/g, '');
};

exports.formatStyle = function(styles = '') {
  const style = [];

  styles.split(/\r|\n/g).forEach(s => {
    const st = s.trim();

    if (st) {
      let [name, value] = st.split(':');
      style.push({ name, value: value.replace(';', '') });
    }
  });

  return style;
};

exports.formatErrorMsg = function(err = {}) {
  if (!err.result) {
    exports.systemError(err);
  }

  return {
    succ: 0,
    msg:
      err.result && err.result.error_msg
        ? err.result.error_msg
        : '服务器出小差了~'
  };
};

exports.getuid = function(length = 6) {
  let chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let name = '';
  let i = 0;

  while (i < length) {
    name += chars[Math.floor(Math.random() * (chars.length - 1) + 1)];
    i++;
  }

  return name;
};

exports.getweeks = function (day='Monday'){
  switch(day){
    case 'Monday':
      return '星期一'
      break;
      case 'Tuesday':
      return '星期二'
      break;
      case 'Wednesday':
      return '星期三'
      break;
      case 'Thursday':
      return '星期四'
      break;
      case 'Friday':
      return '星期五'
      break;
      case 'Saturday':
      return '星期六'
      break;
      case 'Sunday':
      return '星期天'
      break;
      default:
      return '星期一'
      break;
  }
}

exports.Cycles = {
  c_1: '每天',
  c_7: '每周',
  c_14: '每两周',
  c_30: '每月'
};

exports.parseString = (val, _default = '') => (val ? val + '' : _default);

exports.isMiniFunc = ({ _version = '' }) => /mini/.test(_version);
module.exports = exports;